package com.lanyou.cook.upload.service.socket.delfile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

import org.apache.log4j.Logger;

import com.lanyou.cook.upload.commons.Constants;
import com.lanyou.cook.upload.util.ExceptionToStrFactory;
import com.lanyou.cook.upload.util.PropFactory;

public class DelHandlerThread implements Runnable {
	private static Logger logger = Logger.getLogger(DelHandlerThread.class);
	private Socket socket;
	private String filePath;

	/**
	 * @param client
	 *            根据Socket实例创建线程，并启动；默认删除路径是根目录
	 */
	public DelHandlerThread(Socket client) {
		socket = client;
		this.filePath = "/";
		new Thread(this).start();
	}

	/**
	 * @param client
	 *            Socket实例
	 * @param filePath
	 *            删除文件的路径 根据Socket实例、删除文件路径创建线程，并启动
	 */
	public DelHandlerThread(Socket client, String filePath) {
		// logger.info("[DelHandlerThread]:传入的socket："+client+"---文件路径:"+filePath);
		this.filePath = filePath;
		socket = client;
		new Thread(this).start();
	}

	@Override
	public void run() {
		// 定义从客户端读数据的输入流
		InputStream is = null;
		// 定义给客户端发生消息的写出流
		OutputStream out = null;
		try {
			// 获得socket客户端信息的输入流
			is = socket.getInputStream();
			// 获得socket客户端写信息的输出流
			out = socket.getOutputStream();
			// 创建存放读socket客户端传入的字节数组，其大小规定一次最多读入量
			byte[] b = new byte[Integer
					.parseInt(PropFactory
							.getPropByKey(Constants.SOCKET_INPUTSTREAM_SIZE_FOR_FILENAME))];
			// 得到文件名
			int a = is.read(b);
			//判断操作系统
			String os = System.getProperty("os.name"); 
			// 获取文件名
			String filename = new String(b, 0, a);
			String delFileName;
			if(os.toLowerCase().startsWith("win")){
				delFileName= new String(filename.getBytes("gbk"),"utf-8");
			}else{
				delFileName= filename;
			}
			logger.info("[DelHandlerThread.run]：接受到的文件名为：" + delFileName);
			File file = new File(filePath + delFileName);
			boolean delResult = false;
			if (file.exists()) {
				logger.info("[DelHandlerThread.run]：删除" + file.getPath());
				delResult = file.delete();
			}
			if (delResult) {
				logger.info("[DelHandlerThread.run]：删除结果:del success"
						+ file.getPath());
				out.write("delOk".getBytes());
			} else {
				logger.info("[DelHandlerThread.run]：删除结果:del fail"
						+ file.getPath());
				out.write("delFail".getBytes());
			}
		} catch (IOException e) {
			logger.error("[DelHandlerThread.run]："
					+ ExceptionToStrFactory.getErrorInfoFromException(e));
		} finally {
			// 关闭流及socket
			try {
				is.close();
				out.close();
				socket.close();
			} catch (IOException e) {
				logger.error("[DelHandlerThread.run]："
						+ ExceptionToStrFactory.getErrorInfoFromException(e));
			}
		}

	}

	public Socket getSocket() {
		return socket;
	}

	public void setSocket(Socket socket) {
		this.socket = socket;
	}

}
